import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Descriptions, Badge, Button, message, Spin, Divider, Tabs } from 'antd';
import { ArrowLeftOutlined, EditOutlined, ReloadOutlined } from '@ant-design/icons';
import { history, useRequest } from 'umi';
import { getDeviceDetail, updateDeviceStatus, getDeviceTypeOptions, getDeviceStatusOptions } from '@/services/device.js';

const { TabPane } = Tabs;

const DeviceDetail = (props) => {
  const [loading, setLoading] = useState(true);
  const [device, setDevice] = useState({});
  
  // 获取URL参数中的设备ID
  const { id } = props.location.query;
  
  // 设备类型选项
  const deviceTypeOptions = getDeviceTypeOptions();
  
  // 设备状态选项
  const deviceStatusOptions = getDeviceStatusOptions();

  // 获取设备详情
  const fetchDeviceDetail = async () => {
    if (!id) {
      message.error('设备ID不能为空');
      return;
    }
    
    setLoading(true);
    try {
      const response = await getDeviceDetail(id);
      if (response.success) {
        setDevice(response.data);
      } else {
        message.error(response.message || '获取设备详情失败');
      }
    } catch (error) {
      message.error('获取设备详情失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载
  useEffect(() => {
    fetchDeviceDetail();
  }, [id]);

  // 处理更新设备状态
  const handleUpdateStatus = async (status) => {
    try {
      await updateDeviceStatus(id, status);
      message.success('更新设备状态成功');
      fetchDeviceDetail(); // 刷新设备信息
    } catch (error) {
      message.error('更新设备状态失败');
    }
  };

  // 获取设备类型名称
  const getDeviceTypeName = (type) => {
    const typeOption = deviceTypeOptions.find(option => option.value === type);
    return typeOption ? typeOption.label : '未知';
  };

  // 获取设备状态名称和样式
  const getDeviceStatusBadge = (status) => {
    const statusMap = {
      0: { status: 'default', text: '离线' },
      1: { status: 'success', text: '正常' },
      2: { status: 'error', text: '故障' },
    };
    const { status: badgeStatus, text } = statusMap[status] || statusMap[0];
    return <Badge status={badgeStatus} text={text} />;
  };

  // 返回列表页
  const goBack = () => {
    history.push('/device/list');
  };

  // 跳转到编辑页
  const goToEdit = () => {
    history.push(`/device/edit?id=${id}`);
  };

  return (
    <PageContainer
      title="设备详情"
      onBack={goBack}
      extra={[
        <Button key="edit" type="primary" icon={<EditOutlined />} onClick={goToEdit}>
          编辑
        </Button>,
        <Button key="refresh" icon={<ReloadOutlined />} onClick={fetchDeviceDetail}>
          刷新
        </Button>,
      ]}
    >
      <Spin spinning={loading}>
        {device.id ? (
          <>
            <Card title="基本信息" bordered={false}>
              <Descriptions column={2}>
                <Descriptions.Item label="设备ID">{device.id}</Descriptions.Item>
                <Descriptions.Item label="设备编号">{device.device_no}</Descriptions.Item>
                <Descriptions.Item label="设备名称">{device.device_name}</Descriptions.Item>
                <Descriptions.Item label="设备类型">{getDeviceTypeName(device.device_type)}</Descriptions.Item>
                <Descriptions.Item label="所属门店ID">{device.store_id}</Descriptions.Item>
                <Descriptions.Item label="所属房间ID">{device.room_id || '-'}</Descriptions.Item>
                <Descriptions.Item label="状态">
                  {getDeviceStatusBadge(device.status)}
                  <Divider type="vertical" />
                  <a onClick={() => handleUpdateStatus(1)}>设为正常</a>
                  <Divider type="vertical" />
                  <a onClick={() => handleUpdateStatus(0)}>设为离线</a>
                  <Divider type="vertical" />
                  <a onClick={() => handleUpdateStatus(2)}>设为故障</a>
                </Descriptions.Item>
                <Descriptions.Item label="最后在线时间">
                  {device.last_online ? new Date(device.last_online * 1000).toLocaleString() : '-'}
                </Descriptions.Item>
              </Descriptions>
            </Card>

            <Card title="网络信息" bordered={false} style={{ marginTop: 24 }}>
              <Descriptions column={2}>
                <Descriptions.Item label="IP地址">{device.ip_address || '-'}</Descriptions.Item>
                <Descriptions.Item label="MAC地址">{device.mac_address || '-'}</Descriptions.Item>
                <Descriptions.Item label="API密钥">{device.api_key || '-'}</Descriptions.Item>
                <Descriptions.Item label="API接口地址">{device.api_endpoint || '-'}</Descriptions.Item>
              </Descriptions>
            </Card>

            <Card title="硬件信息" bordered={false} style={{ marginTop: 24 }}>
              <Descriptions column={2}>
                <Descriptions.Item label="制造商">{device.manufacturer || '-'}</Descriptions.Item>
                <Descriptions.Item label="型号">{device.model || '-'}</Descriptions.Item>
                <Descriptions.Item label="固件版本">{device.firmware || '-'}</Descriptions.Item>
                <Descriptions.Item label="描述">{device.description || '-'}</Descriptions.Item>
              </Descriptions>
            </Card>
          </>
        ) : (
          !loading && <div style={{ textAlign: 'center' }}>未找到设备信息</div>
        )}
      </Spin>
    </PageContainer>
  );
};

export default DeviceDetail;